package com.wanxing.sellerapp.emqx.handlers

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.blankj.utilcode.util.ShellUtils
import com.blankj.utilcode.util.ThreadUtils
import com.wanxing.sellerapp.App
import com.wanxing.sellerapp.audio.AudioHelper
import com.wanxing.sellerapp.config.EmqxConfig
import com.wanxing.sellerapp.emqx.entity.EmqMessage
import com.wanxing.sellerapp.emqx.entity.EmqPayload
import com.wanxing.sellerapp.emqx.enums.ActionEnum
import com.wanxing.sellerapp.emqx.interfaces.IMessenger
import com.wanxing.sellerapp.seller.SellerManager


/**
 * 不走服务器的在线调试
 */
class DebugHandler(messenger: IMessenger, sellerManager: SellerManager) : AbstractActionHandler(messenger, sellerManager) {

    val REQ_ZERO = "ZERO"

    val REQ_CALIBRATE = "CALIBRATE"

    val REQ_ZERO_DOOR = "ZERO_DOOR"

    val REQ_CALIBRATE_DOOR = "CALIBRATE_DOOR"

    val REQ_OPEN_DOOR = "OPEN_DOOR"

    val REQ_CLOSE_DOOR = "CLOSE_DOOR"

    val REQ_QUERY_WEIGHT = "QUERY_WEIGHT"

    val REQ_REBOOT = "REBOOT"


    override fun handleAction(messageId: String?, data: JSONObject, payload: EmqPayload) {
        when (data.getString("req")) {
            REQ_OPEN_DOOR -> openDoor(data)
            REQ_CLOSE_DOOR -> closeDoor(data)
            REQ_REBOOT -> reboot()
        }
    }

    private fun reboot() {
        ThreadUtils.runOnUiThreadDelayed({ ShellUtils.execCmd("reboot", true, false)}, 600)
    }

    private fun openDoor(data: JSONObject){
        val doorNo = data.getIntValue("doorNo")
        val openSuccess  = try {
            sellerManager.seller.openDoor(doorNo)
        }catch (e: InterruptedException){
            false
        }
        if (openSuccess){
            AudioHelper.play(AudioHelper.SOUND_DOOR_OPEN_SUC)
        }else{
            AudioHelper.play(AudioHelper.SOUND_DOOR_OPEN_FAIL)
        }
    }

    private fun closeDoor(data: JSONObject){
        val doorNo = data.getIntValue("doorNo")
        val closeDoorSuccess  = try { sellerManager.seller.closeDoor(doorNo) }
                         catch (e: InterruptedException){ false }
        if (closeDoorSuccess){
            AudioHelper.play(AudioHelper.SOUND_DOOR_CLOSE_SUC)
        }else{
            AudioHelper.play(AudioHelper.SOUND_DOOR_CLOSE_FAIL)
        }
    }

}